// Copyright (c) Microsoft Corporation. All rights reserved.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Xml.Serialization;

using Microsoft.TeamFoundation.Migration.Toolkit.Wit;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace Microsoft.TeamFoundation.Migration.Toolkit.Linking
{
    /// <summary>
    /// Link to a VC change list
    /// </summary>
    [Serializable]
    public class WorkItemChangeListLink: WorkItemExternalLinkBase
    {
        /// <summary>
        /// Parameterless constructor for serialization.
        /// </summary>
        public WorkItemChangeListLink()
        {
        }

        /// <summary>
        /// Public constructor for version control change lists.
        /// </summary>
        /// <param name="sourceUri">Source artifact</param>
        /// <param name="targetUri">URI of the linked version control item</param>
        /// <param name="comment">Link's comment</param>
        public WorkItemChangeListLink(
            string sourceUri,
            string targetUri,
            string comment)
            : base(LinkingConstants.VcChangelistLinkType, sourceUri, targetUri, comment)
        {
            if (!TfsChangelistHandler.IsMyUri(targetUri))
            {
                throw new ToolkitArgException("targetUri");
            }
        }

        /// <summary>
        /// Creates a copy of the link pointing to the new target.
        /// </summary>
        /// <param name="id">Id of the new target</param>
        /// <returns>Link copy</returns>
        public override ILink Redirect(string targetUri)
        {
            if (string.IsNullOrEmpty(targetUri))
            {
                throw new ArgumentNullException("targetUri");
            }
            return new WorkItemChangeListLink(SourceUri, targetUri, Comment);
        }

        /// <summary>
        /// Checks whether the external link points to a version control object.
        /// </summary>
        /// <param name="l">External link</param>
        /// <returns>True if the link points to a change set</returns>
        internal static bool IsMyLink(
            ExternalLink l)
        {
            return TFStringComparer.ArtifactType.Equals(l.ArtifactLinkType.Name, LinkingConstants.VcChangelistLinkType)
                && TfsChangelistHandler.IsMyUri(l.LinkedArtifactUri);
        }
    }
}
